package com.zerosky.crm.util;

import java.io.FileInputStream;
import java.io.IOException;  
import java.io.InputStreamReader;  
import java.io.LineNumberReader; 
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.awt.Container;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;

import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.FileImageInputStream;
import javax.imageio.stream.ImageInputStream;

import com.sun.image.codec.jpeg.*;
import com.sun.imageio.plugins.png.PNGImageReader;
import com.sun.imageio.plugins.png.PNGMetadata;
  
public class IMGTOOL {  
  
 //   private static String CMYK_COMMAND = "mogrify -colorspace RGB -quality 80 file1";//转换cmyk格式  
      
//    public static void setCMYK_COMMAND(String file1) {        
//        exeCommand(CMYK_COMMAND.replace("file1", file1));        
//    }        
       
    
    /**
	 *
	 * @param f 图片输出路径
	 * @param filelist 图片路径
	 * @param ext 缩略图扩展名
	 * @param n 图片名
	 * @param w 目标宽
	 * @param h 目标高
	 * @param per 百分比
	 */
	    public static void  Tosmallerpic(File oldFile,File newFile,int width,int height,float quality){
	         if(!newFile.getParentFile().exists()){
	         newFile.getParentFile().mkdirs();
	         }
	            Image src=null;
	            BufferedImage tag=null;
	            FileOutputStream newimage=null;
	            try {
	             try{
	              src = javax.imageio.ImageIO.read(oldFile); //构造Image对象
	             }catch(Exception e){
	              e.printStackTrace();
	               //  logger.info(oldFile.getName()+"图片的ICC信息可能已经被破坏开始转换:");
	                    try {
	                      IMGTOOL convert=new IMGTOOL();
	                      //convert.setCMYK_COMMAND(oldFile.getPath());
	                      String CMYK_COMMAND = "mogrify -colorspace RGB -quality 100 file1";//转换cmyk格式
	                      convert.exeCommand(CMYK_COMMAND.replace("file1",oldFile.getPath()));
	                      src = Toolkit.getDefaultToolkit().getImage(oldFile.getPath());
	                      MediaTracker mediaTracker = new MediaTracker(new Container());
	                      mediaTracker.addImage(src, 0);
	                      mediaTracker.waitForID(0);
	                      src.getWidth(null);
	                      src.getHeight(null);
	                    }catch (Exception e1){
	                        e1.printStackTrace();
	                    }
	               }
	               //,String ext 保留字段 缩略图拼接字段
	               //String img_midname=newFile;
	               int old_w=src.getWidth(null)==-1?width:src.getWidth(null); //得到源图宽
	               int old_h=src.getHeight(null)==-1?height:src.getHeight(null);
	               
	               int new_w=0;
	               int new_h=0; //得到源图长

	               double w2=(old_w*1.00)/(width*1.00);
	               double h2=(old_h*1.00)/(height*1.00);

	                //图片调整为方形结束
	               if(old_w>width)
	               new_w=(int)Math.round(old_w/w2);
	               else
	                   new_w=old_w;
	               if(old_h>height)
	               new_h=(int)Math.round(old_h/h2);//计算新图长宽
	               else
	                   new_h=old_h;
	               
	               //tag.getGraphics().drawImage(src,0,0,new_w,new_h,null); //绘制缩小后的图
	               //设置新的图片尺寸
	              // tag = new BufferedImage(new_w,new_h,BufferedImage.TYPE_INT_RGB);    
	              // tag.getGraphics().drawImage(src.getScaledInstance(new_w, new_h,  Image.SCALE_SMOOTH), 0,0,null);
	               //原图尺寸
	               tag = new BufferedImage(old_w, old_h,BufferedImage.TYPE_INT_RGB);  
	               tag.getGraphics().drawImage(src.getScaledInstance(old_w, old_h,  Image.SCALE_SMOOTH), 0,0,null);
	               newimage=new FileOutputStream(newFile); //输出到文件流
	               JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(newimage);
	               JPEGEncodeParam jep=JPEGCodec.getDefaultJPEGEncodeParam(tag);
	                /* 压缩质量 */
	               jep.setQuality(quality, true);
	               encoder.encode(tag, jep);
	               //encoder.encode(tag); //近JPEG编码
	               newimage.close();
	            } catch (Exception ex) {
	             ex.printStackTrace();
	            // logger.info(oldFile.getName()+"图片压缩问题;"+ex);
	                //Logger.getLogger(File:mpress.class.getName()).log(Level.SEVERE, null, ex);
	            }finally{
	             if(newimage!=null){
	              try {
	            	  newimage.close();
	     } catch (Exception e) {
	      e.printStackTrace();
	     }
	             }
	             if(tag!=null){
	              tag.flush();
	             }
	            }
	    } 
	    // 图片处理
		public static List compressPic(String inputDir, String outputDir, String inputFileName, String outputFileName,int outputWidth,int outputHeight) {
//			String inputDir; // 输入图路径  
//		    String outputDir = null; // 输出图路径  
//		    String inputFileName; // 输入图文件名  
//		    String outputFileName = null; // 输出图文件名  
//		    int outputWidth = 600; // 默认输出图片宽  
//		    int outputHeight = 600; // 默认输出图片高  
		    boolean proportion = true; // 是否等比缩放标记(默认为等比缩放)  
			List list = new ArrayList();
	        try {
				File file = new File(inputDir+inputFileName); 
	            //获得源文件 
	            if (!file.exists()) {   
	                return null;   
	            }   
	            Image img = ImageIO.read(file);   
	            // 判断图片格式是否正确   
	            if (img.getWidth(null) == -1) {  
	                System.out.println(" can't read,retry!" + "<BR>");   
	                return null;   
	            } else {   
	                int newWidth; int newHeight;   
	                // 判断是否是等比缩放   
	                if (proportion == true) {   
	                    // 为等比缩放计算输出的图片宽度及高度   
	                    double rate1 = ((double) img.getWidth(null)) / (double) outputWidth + 0.1;   
	                    double rate2 = ((double) img.getHeight(null)) / (double) outputHeight + 0.1;   
	                    // 根据缩放比率大的进行缩放控制   
	                    double rate = rate1 > rate2 ? rate1 : rate2;   
	                    newWidth = (int) (((double) img.getWidth(null)) / rate);   
	                    newHeight = (int) (((double) img.getHeight(null)) / rate);   
	                } else {   
	                    newWidth = outputWidth; // 输出的图片宽度   
	                    newHeight = outputHeight; // 输出的图片高度   
	                }   
	               BufferedImage tag = new BufferedImage((int) newWidth, (int) newHeight, BufferedImage.TYPE_INT_RGB);   
	                 
	               /* 
	                * Image.SCALE_SMOOTH 的缩略算法 生成缩略图片的平滑度的 
	                * 优先级比速度高 生成的图片质量比较好 但速度慢 
	                */   
	               tag.getGraphics().drawImage(img.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH), 0, 0, null); 
	       		   File fil = new File(outputDir);
				   if (!fil.exists()) {//若无文件夹则创建
					   fil.mkdirs();
				   } 
	               FileOutputStream out = new FileOutputStream(outputDir+outputFileName);  
	               // JPEGImageEncoder可适用于其他图片类型的转换   
	               JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);   
	               encoder.encode(tag);   
	               out.close();
	               list.add("/compressPic/"+outputFileName);
	               list.add(newWidth);
	               list.add(newHeight);
	               list.add(3, 0);
	            }   
	        } catch (IOException ex) {
	        	list.add(3, -1);
	            ex.printStackTrace();   
	        }   
	        return list;   
	   }   
	    /** 
	     * @param srcFile源文件 
	     * @param outFile输出文件 
	     * @param x坐标 
	     * @param y坐标 
	     * @param width宽度 
	     * @param height高度 
	     * @return 
	     * @创建日期 2012-8-2 
	     * @创建时间 下午02:05:03 
	     * @描述 —— 裁剪图片 
	     */  
	    public static boolean cutPic(String srcFile, String outFile, int x, int y,  
	            int width, int height) {  
	        FileInputStream is = null;  
	        ImageInputStream iis = null;  
	        try {  
	            // 如果源图片不存在  
	            if (!new File(srcFile).exists()) {  
	                return false;  
	            }  
	  
	            // 读取图片文件  
	            is = new FileInputStream(srcFile); 
	            if(width>height){
	            	x = (width-height)/2;
	            	y = 1;
	            	width = height;
	            }else if(width<height){
	            	x = 1;
	            	y = (height-width);
	            	height = width;
	            }
	  
	            // 获取文件格式  
	            String ext = srcFile.substring(srcFile.lastIndexOf(".") + 1);  
	  
	            // ImageReader声称能够解码指定格式  
	            //Iterator<ImageReader> it = ImageIO.getImageReadersByFormatName(ext);
	            Iterator<ImageReader> it = ImageIO.getImageReaders(new FileImageInputStream(new File(srcFile)));
	            ImageReader reader = it.next();  
	  
	            // 获取图片流  
	            iis = ImageIO.createImageInputStream(is);  
	  
	            // 输入源中的图像将只按顺序读取  
	            reader.setInput(iis, true);  
	  
	            // 描述如何对流进行解码  
	            ImageReadParam param = reader.getDefaultReadParam();  
	  
	            // 图片裁剪区域  
	            Rectangle rect = new Rectangle(x, y, width, height);  
	  
	            // 提供一个 BufferedImage，将其用作解码像素数据的目标  
	            param.setSourceRegion(rect);  
	  
	            // 使用所提供的 ImageReadParam 读取通过索引 imageIndex 指定的对象  
	            BufferedImage bi = reader.read(0, param);  
	  
	            // 保存新图片  
	            File tempOutFile = new File(outFile);  
	            if (!tempOutFile.exists()) {  
	                tempOutFile.mkdirs();  
	            }  
	            ImageIO.write(bi, ext, new File(outFile));
	            return true;  
	        } catch (Exception e) {  
	            e.printStackTrace();  
	            return false;  
	        } finally {  
	            try {  
	                if (is != null) {  
	                    is.close();  
	                }  
	                if (iis != null) {  
	                    iis.close();  
	                }  
	            } catch (IOException e) {  
	                e.printStackTrace();  
	                return false;  
	            }  
	        }  
	    }  
    
    public static boolean exeCommand(String cmd){        
        InputStreamReader ir = null;        
        LineNumberReader input = null;        
        try        
        {        
            //linux下java执行指令：Runtime.getRuntime().exec (String str);        
            Process process = Runtime.getRuntime().exec (cmd);        
            ir=new InputStreamReader(process.getInputStream());        
            input = new LineNumberReader (ir);        
            while ((input.readLine ()) != null){        
            }        
            ir.close();        
            input.close();        
            }        
        catch (IOException e){        
            e.printStackTrace();  
        return false;        
        }        
       return true;        
    }       
  
    
    
    
    /**
     * 获取图片的拍摄时间
     * @param jpegFile
     * @return
     */
    
  /*  public static Date getImgDate(File jpegFile){
    	
    	Date date = null;
		
		try {
			Metadata metadata = JpegMetadataReader.readMetadata(jpegFile);
			Directory exifDirectory = metadata.getDirectory(ExifDirectory.class);
			
				if (exifDirectory.containsTag(ExifDirectory.TAG_DATETIME)){
					try {
						date = exifDirectory.getDate(ExifDirectory.TAG_DATETIME);
					} catch (MetadataException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
		} catch (JpegProcessingException e) {
			e.printStackTrace();
		}
    	return date;
    }*/
    
    
    /**
     * 获取图片的拍摄时间
     * @param jpegFile
     * @return
     */
    
//    public static String getImgDate(File jpegFile){
//    	
//    	//Date date = null;
//    	Date date = null;
//		try {
//			
//			Metadata metadata = ImageMetadataReader.readMetadata(jpegFile);
//			
//			Directory exifDirectory = metadata.getDirectory(ExifDirectory.class);
//			
//			if (exifDirectory.containsTag(ExifDirectory.TAG_DATETIME)){
//				try {
//					date = exifDirectory.getDate(ExifDirectory.TAG_DATETIME);
//					// System.out.println(date);
//				} catch (MetadataException e) {
//				 
//				e.printStackTrace();
//				}
//			}
//			
////			
////			for (Directory directory : metadata.getDirectory(ExifDirectory.class)) {
////	            for (Tag tag : directory.getTags()) {
////	                String tagName = tag.getTagName();
////	                String desc = tag.getDescription();
////	                
////	                if (tagName.equals("Date/Time Original")){
////	                	date = desc;
////	                }
////	                		
//////	                if (tagName.equals("Image Height")) {
//////	                    //图片高度
//////	                    imgInfoBean.setImgHeight(desc);
//////	                } else if (tagName.equals("Image Width")) {
//////	                    //图片宽度
//////	                    imgInfoBean.setImgWidth(desc);
//////	                } else if (tagName.equals("Date/Time Original")) {
//////	                    //拍摄时间
//////	                    imgInfoBean.setDateTime(desc);
//////	                } else if (tagName.equals("GPS Altitude")) {
//////	                    //海拔
//////	                    imgInfoBean.setAltitude(desc);
//////	                } else if (tagName.equals("GPS Latitude")) {
//////	                    //纬度
//////	                    imgInfoBean.setLatitude(pointToLatlong(desc));
//////	                } else if (tagName.equals("GPS Longitude")) {
//////	                    //经度
//////	                    imgInfoBean.setLongitude(pointToLatlong(desc));
//////	                }
////	            }
////	            
////	        } 
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//    	return "";
//    }
//    
    public static void main(String[] args) {
    	
    	//String oldpath="D:/102301556558752285.jpg";
		//  String newpath="D:\\000.jpg";
		//  Tosmallerpic(new File(oldpath),new File(newpath), 300, 200, 0.5f);图片压缩
    	
//    	
//    	File jpegFile = new File("F:/QQ_Images/5b8d021fe2ee6194.jpg");
//    	Date aa=getImgDate(jpegFile);//获取图片拍摄时间
//    	System.out.println(aa);
//    	getImgDate(jpegFile);

		String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
		String a="";
		for(int i=0;i<4;i++){
			a=a+chars.charAt((int)(Math.random() * 26));
		}
		System.out.println(a+((int)(Math.random() * 90000000)+10000000));
	}
    
}  